package servlet;

import entity.Page;
import entity.User;
import service.UserService;
import service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "QueryUsersByPageServlet", value = "/QueryUsersByPageServlet")
public class QueryUsersByPageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String currentPage=request.getParameter("currentPage");
        String search=request.getParameter("search");
        UserService userService=new UserServiceImpl();
        Page page=new Page();
        currentPage=(currentPage==null?"0":currentPage);
        page.setCurrentPage(Integer.parseInt(currentPage));
        if(search==null||"null".equals(search)){  //search用来判断是查询全部还是条件查询
            String sql="select count(*) from users";
            int count=userService.getUserTatalCount(sql,null);
            page.setTotalCount(count);
            page.setPageSize(10);
            List<User> users=userService.queryStudentByPage(page.getCurrentPage(),page.getPageSize());
            page.setUser(users);
            request.setAttribute("page",page);
            request.getSession().setAttribute("search",search);
            request.getRequestDispatcher("user.jsp").forward(request,response);
        }else{
            String sql="select count(*) from users where userId=? or userName=?";
            Object[] params={search,search};
            int count=userService.getUserTatalCount(sql,params);
            page.setTotalCount(count);
            page.setPageSize(10);
            List<User> users=userService.queryUserByPageRequire(page.getCurrentPage(), page.getPageSize(),search);
            page.setUser(users);
            request.setAttribute("page",page);
            request.getSession().setAttribute("search",search);
            request.getRequestDispatcher("user.jsp").forward(request,response);
        }
    }
}
